package cn.ligoo.dtu.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Properties;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import cn.ligoo.dtu.server.codec.DtuCodecFactory;

/**
 * DTU Server Powered by Mina
 * 
 * @author qinghua.jin@ligoo.cn
 * @version 2012
 * 
 */
public class DtuServer {
	private static final Logger LOGGER = LoggerFactory.getLogger(DtuServer.class);

	public static void main(String[] args) throws IOException {
		Properties props = PropertiesLoaderUtils.loadAllProperties("dtu-server.properties");
		int port = Integer.parseInt(props.getProperty("dtu-server.port", "7777"));
		int idleTime = Integer.parseInt(props.getProperty("dtu-server.idleTime", "30"));
		Charset charset = Charset.forName(props.getProperty("dtu-server.charset", "UTF-8"));

		LOGGER.info("availableProcessors:{}", Runtime.getRuntime().availableProcessors());
		IoAcceptor acceptor = new NioSocketAcceptor();

		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new DtuCodecFactory(charset)));

		acceptor.setHandler(new DtuServerIoHandler());

		acceptor.getSessionConfig().setReadBufferSize(100);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTime);

		acceptor.bind(new InetSocketAddress(port));
		LOGGER.info("Ligoo DTU Server started, bind port:{}", port);
	}
}